<script setup lang="ts">
import { CirclePlus } from '@element-plus/icons-vue'
import formButton from '@renderer/components/formButton.vue'
import useCompute from '@renderer/composables/useCompute'
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, Action, type CascaderProps, type CascaderValue } from 'element-plus'
import useUtil from '@renderer/composables/useUtil'
import useCommon from '@renderer/composables/useCommon'
import dayjs from 'dayjs'
import NavBar from '@renderer/components/navBar.vue'
import useStorage from '@renderer/composables/useStorage'
import { CacheEnum } from '@renderer/enum/CacheEnum'
import useComputeForm from '@renderer/composables/useComputeForm'
import helper from '@renderer/utils/helper'
import { ApiEnum } from '@renderer/enum/ApiEnum'
import { http } from '@renderer/plugins/axios'
const initParams = () => ({
  keywords: '',
  designer: '0',
  status: '-1',
  date: '',
  date_type: '0',
  page: 1,
  limit: 10,
})
const initSubmitForm = () => ({
  name: '',
  template: 2,
  calculate_id: '',
  house_number: '',
  mode: 1,
})
const storage = useStorage()
const calculateQuery = reactive(initParams())
const submitForm = reactive(initSubmitForm())
const designerName = ref('')
const templateType = ref('')
const templateTypeOptions = ref([{ label: '公司模板' }, { label: '财多多模板' }])
const houseTypeOptions = ref([
  { id: 1, label: '平层' },
  { id: 2, label: '二层' },
  { id: 3, label: '三层' },
  { id: 4, label: '四层' },
  { id: 5, label: '五层' },
])
const loadPage = ref(1)
const identityList = ref<string[]>([])
const ids = ref([])
const templateOptions = ref<{ value: string; label: string; house_number: string }[]>([])
const currentType = ref<initType>('init')
const addComputeDialog = ref(false)
const isShow = ref(false)
const currentInfo = ref<CalculateModel>()
const makeComputeDialog = ref(false)
const templateDialog = ref(false)
const templateTitle = ref('')
const calculateTitle = ref('')
const companyInfo = ref<CompanyModel>()
const statusOptions = [
  {
    value: '-1',
    label: '全部',
  },
  {
    value: '1',
    label: '已签单',
  },
  {
    value: '2',
    label: '未签单',
  },
  {
    value: '3',
    label: '已关联',
  },
]
const designerProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level, data } = node
    setTimeout(async () => {
      let nodes
      switch (level) {
        case 0:
          identityList.value = []
          identityList.value = await handleGetIdentity()
          identityList.value.unshift('全部')
          nodes = identityList.value.map((item) => ({
            value: '',
            label: item,
            leaf: item == '全部' ? true : level >= 1,
          }))
          break
        case 1:
          await getStaff({
            type: data?.label,
            scene: 1,
          })
          if (peopleList.value?.length) {
            nodes = peopleList.value.map((item) => ({
              value: item.id,
              label: item.name,
              leaf: level >= 1,
            }))
          }
          break
      }
      resolve(nodes)
    }, 1000)
  },
} as CascaderProps

const handleQuery = async () => {
  currentType.value = 'search'
  await initData(currentType.value, 1)
}
const handleReset = async () => {
  Object.assign(calculateQuery, initParams())
  currentType.value = 'init'
  designerName.value = ''
  await initData('init', 1)
}
const handleNextPage = async (val: number) => {
  await initData(currentType.value, val)
}
const change = (value: CascaderValue) => {
  calculateQuery.designer = value[1] ? value[1] : '0'
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
}
const handleDel = async () => {
  if (!ids.value.length) {
    ElMessage({ type: 'error', message: '请先选择需要删除的预算，再删除。' })
    return
  }
  ElMessageBox.alert(`您确定要删除选择的预算吗？`, '温馨提示', {
    showCancelButton: true,
    callback: async (action: Action) => {
      if (action == 'confirm') {
        await delCalculate({
          ids: ids.value,
        })
        ids.value = []
        await initData('init', 1)
      }
    },
  })
}
const initData = async (type: initType, page: number) => {
  const params = {
    keywords: type == 'init' ? '' : calculateQuery.keywords,
    designer: type == 'init' ? '0' : calculateQuery.designer,
    status: type == 'init' ? '-1' : calculateQuery.status,
    date: type == 'init' ? '' : calculateQuery.date ? dayjs(calculateQuery.date).format('YYYY-MM') : '',
    date_type: type == 'init' ? '0' : calculateQuery.date ? '2' : '',
    page,
    limit: calculateQuery.limit,
  }
  await getCalculateList(params)
  companyInfo.value = await storage.get(CacheEnum.COMPANY_INFO)
}
const handleAddCompute = async () => {
  if (checkRule('预算明细修改权')) {
    const res = await http.request<{ userInfo: UserModel; companyInfo: CompanyModel }>({
      url: ApiEnum.CURRENT_USER,
    })
    isShow.value = res.companyInfo.mode == 2 ? true : false
    addComputeDialog.value = true
  } else {
    ElMessage({ type: 'error', message: '抱歉！您没有此权限' })
  }
}
const getTemplateList = async (template_type: number) => {
  const templateList: ApiPage<TemplateComputeModel> = await getCalculateTemplateList({
    page: loadPage.value,
    limit: 10,
    template_type,
  })
  if (templateList.data.length > 0) {
    templateList.data.forEach((item) => {
      templateOptions.value.push({
        value: item.id + '',
        label: item.name,
        house_number: item.house_number,
      })
    })
  } else {
    ElMessage({ type: 'error', message: '抱歉！已全部加载完成' })
  }
}
const onLoadmore = async () => {
  loadPage.value++
  await getTemplateList(templateType.value == '公司模板' ? 2 : 1)
}
const handleTemplateTypeChange = async (event) => {
  templateOptions.value = []
  loadPage.value = 1
  await getTemplateList(event == '公司模板' ? 2 : 1)
}
const handleTemplateChange = async (event) => {
  const templateInfo = templateOptions.value.find((item) => item.value == event)
  submitForm.house_number = templateInfo?.house_number!
  isShow.value = false
  submitForm.mode = 1
}
const visibleChange = (event) => {
  if (event && !templateType.value) {
    ElMessage({ type: 'error', message: '抱歉！请先选择模板类型' })
  }
}
const handleClose = async () => {
  Object.assign(submitForm, initSubmitForm())
  templateType.value = ''
  addComputeDialog.value = false
  await initData('init', 1)
}
const handleSave = async () => {
  if (!submitForm.name) {
    ElMessage.error('请输入预算名称')
    return
  }
  if (!submitForm.house_number) {
    ElMessage.error('请选择房屋类型')
    return
  }
  submitForm.calculate_id = submitForm.calculate_id ? submitForm.calculate_id : '0'
  await createCalculateGather(submitForm)
  handleClose()
}
const handleDetail = async (item: CalculateModel) => {
  await getCalculateDetail({
    calculate_id: item.id,
    house_number: item.house_number,
  })
  if (calculateInfo.value?.check_gather == 2) {
    ElMessage({ type: 'error', message: '请先提交“数据采集”数据' })
    return
  }
  await storage.set(CacheEnum.MENU_TYPE, calculateInfo.value?.type == 1 ? 'templateOne' : 'templateTwo')
  window.api.closeWindow('basiceQuipment', 'destroy')
  window.api.closeWindow('total', 'destroy')
  window.api.openWindow(calculateInfo.value?.type == 1 ? 'basiceQuipment' : 'total', {
    title: '预算成本明细',
    calculate_id: calculateInfo.value?.id,
    house_number: calculateInfo.value?.house_number,
    calculate_name: calculateInfo.value?.name,
    house_type: calculateInfo.value?.type,
  })
}
const handleCollectionData = async (item: CalculateModel) => {
  if (checkRule('预算明细修改权')) {
    if (item.house_number == 1) {
      window.api.closeWindow('collectionData', 'destroy')
      window.api.openWindow('collectionData', {
        title: '数据采集',
        calculate_id: item.id,
        house_number: item.house_number,
        isSave: '1',
        type: '单',
      })
      await storage.set('calcalateHouseNumber', item.house_number)
    } else {
      currentInfo.value = calculateList.value?.data.find((calculateItem) => calculateItem.id == item.id)
      await getHousesInfo(item.id, item.house_number)
    }
  } else {
    ElMessage({ type: 'error', message: '抱歉！您没有此权限' })
  }
}
const getHousesInfo = async (calculate_id, house_number) => {
  await getGatherCount({ calculate_id })
  makeComputeDialog.value = true
  await storage.set('calcalateHouseNumber', house_number)
}
const handleCollectData = (house_number: number) => {
  window.api.closeWindow('collectionData', 'destroy')
  window.api.openWindow('collectionData', {
    title: handleRoomName(house_number),
    calculate_id: currentInfo.value?.id,
    house_number,
    isSave: '0',
    type: '多',
  })
}
const handleSetting = (item: CalculateModel) => {
  window.api.openWindow('settingCompute', {
    title: '预算设置',
    calculate_id: item.id,
    house_number: item.house_number,
    check_gather: item.check_gather,
  })
}
const handleRoomName = (house_number) => {
  switch (house_number * 1) {
    case 1:
      return '一层数据采集'
    case 2:
      return '二层数据采集'
    case 3:
      return '三层数据采集'
    case 4:
      return '四层数据采集'
    case 5:
      return '五层数据采集'
    default:
      return '数据采集'
  }
}
const handleCopy = () => {
  const calculateInfo = calculateList.value?.data.find((item) => item.id == ids.value[0])
  templateTitle.value = calculateInfo?.template == 1 ? '复制模版' : '复制预算'
  templateDialog.value = true
}
const handleResetName = () => {
  const calculateInfo = calculateList.value?.data.find((item) => item.id == ids.value[0])
  templateTitle.value = '重命名'
  calculateTitle.value = calculateInfo?.name!
  templateDialog.value = true
}
const handleSign = () => {
  const calculateInfo = calculateList.value?.data.find((item) => item.id == ids.value[0])
  if (calculateInfo?.check_gather == 2) {
    ElMessage({ type: 'error', message: '因未提交数据采集，无法打开签单状态' })
    return
  }
  ElMessageBox.alert(`是否要更改${calculateInfo?.name}的签单状态？`, '温馨提示', {
    showCancelButton: true,
    callback: async (action: Action) => {
      if (action == 'confirm') {
        await setSignBill({
          id: calculateInfo?.id,
          status: calculateInfo?.status == 2 ? 1 : 2,
          type: 1,
        })
        await initData('init', 1)
      }
    },
  })
}
const handleTemplateSave = async () => {
  if (templateTitle.value == '重命名') {
    await updateCalculateName({
      id: ids.value[0],
      name: calculateTitle.value,
    })
  } else {
    await copyGather({
      calculate_id: ids.value[0],
      name: calculateTitle.value,
    })
  }
  handleTemplateClose()
  await initData('init', 1)
}
const handleTemplateClose = () => {
  templateTitle.value = ''
  calculateTitle.value = ''
  templateDialog.value = false
}
const {
  getCalculateList,
  calculateList,
  setSignBill,
  getCalculateTemplateList,
  createCalculateGather,
  updateCalculateName,
  copyGather,
  delCalculate,
  getGatherCount,
  housesInfo,
} = useCompute()
const handleMakeComputeClose = () => {
  makeComputeDialog.value = false
}
const handleHouse = (number: number) => {
  switch (number) {
    case 1:
      return '平层'
    case 2:
      return '两层'
    case 3:
      return '三层'
    case 4:
      return '四层'
    case 5:
      return '五层'
    default:
      return ''
  }
}
const handleSubmit = async () => {
  await submitGather({
    calculate_id: currentInfo.value?.id,
  })
  await getCalculateDetail({
    calculate_id: currentInfo.value?.id,
    house_number: currentInfo.value?.house_number,
  })
  await initData('init', 1)
}
const handleResetData = async () => {
  ElMessageBox.alert('重新提交核算会覆盖掉部分数值，您是否继续重新提交核算？ ', '温馨提示', {
    showCancelButton: true,
    callback: async (action: Action) => {
      if (action == 'confirm') {
        await reGather({
          calculate_id: currentInfo.value?.id,
        })
        await getCalculateDetail({
          calculate_id: currentInfo.value?.id,
          house_number: currentInfo.value?.house_number,
        })
        await initData('init', 1)
      }
    },
  })
}
const { getCalculateDetail, calculateInfo, submitGather, reGather } = useComputeForm()
const { handleGetIdentity, handleHousePic } = useUtil()
const { checkRule } = helper()
const { getStaff, peopleList } = useCommon()
window.api.refreshData(async () => {
  await initData('init', 1)
})
await initData('init', 1)
</script>

<template>
  <main class="bg-white flex flex-col gap-3 rounded-md" style="height: -webkit-fill-available">
    <el-form :model="calculateQuery" inline>
      <el-form-item label="预算名称">
        <el-input v-model="calculateQuery.keywords" placeholder="请输入预算名称" clearable />
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker v-model="calculateQuery.date" type="month" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="制作人">
        <el-cascader :props="designerProps" v-model="designerName" @change="change" />
      </el-form-item>
      <el-form-item label="预算状态">
        <el-select v-model="calculateQuery.status" placeholder="请选择">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="flex justify-end gap-3">
      <formButton @click="handleDel"> 删除 </formButton>
      <formButton v-if="ids.length == 1" @click="handleCopy"> 复制 </formButton>
      <formButton v-if="ids.length == 1" @click="handleResetName"> 重命名 </formButton>
      <formButton v-if="ids.length == 1" @click="handleSign"> 签单状态 </formButton>
      <formButton @click="handleQuery"> 搜索 </formButton>
      <formButton @click="handleReset"> 重置 </formButton>
      <formButton @click="handleReset"> 刷新 </formButton>
      <formButton class="flex items-center" @click="handleAddCompute">
        <el-icon class="mr-1" :size="18"><CirclePlus /></el-icon>
        新增预算
      </formButton>
    </div>
    <el-table
      :data="calculateList?.data"
      border
      header-align="center"
      :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" width="58" />
      <el-table-column prop="name" label="预算名称" align="center" />
      <el-table-column prop="create_time" label="创建日期" align="center" width="104">
        <template #default="scope">
          {{ dayjs(scope.row.create_time).format('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column prop="user.name" label="制作人" align="center" width="70" />
      <el-table-column prop="template" label="类型" align="center" width="57">
        <template #default="scope">
          {{ scope.row.template == '1' ? '模版' : '预算' }}
        </template>
      </el-table-column>
      <el-table-column prop="check_lock" label="关联状态" align="center" width="85">
        <template #default="scope">
          {{ scope.row.check_lock == 1 ? '已关联' : '未关联' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否签单" align="center" width="85">
        <template #default="scope">
          {{ scope.row.template == '1' ? '无' : scope.row.status == 1 ? '已签单' : '未签单' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="预算类型" align="center" width="90">
        <template #default="scope">
          {{ companyInfo?.mode == 2 ? (scope.row.mode == 1 ? '分项' : '大包') : '' }}
          {{ handleHouse(scope.row.house_number) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="172">
        <template #default="scope">
          <el-button
            :type="scope.row.check_gather == 1 ? 'warning' : 'primary'"
            plain
            size="small"
            @click="handleCollectionData(scope.row)">
            做预算
          </el-button>
          <el-button
            type="warning"
            plain
            size="small"
            @click="handleSetting(scope.row)"
            v-if="checkRule('核算方式修改权') || checkRule('损耗系数修改权') || checkRule('材料规格修改权')"
            >预算设置</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="明细" align="center" width="100">
        <template #default="scope">
          <el-button
            :type="scope.row.check_gather == 2 ? 'info' : 'warning'"
            plain
            size="small"
            @click="handleDetail(scope.row)">
            查看明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleNextPage"
      :current-page="calculateList?.current_page"
      :page-size="calculateQuery.limit"
      :total="calculateList?.total"
      background
      hide-on-single-page
      class="flex-1 items-end" />
    <el-dialog v-model="addComputeDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleClose" title="新增预算" />
        <el-form :model="submitForm" class="px-6 pt-6 flex flex-col gap-6">
          <el-form-item label="预算标题:" required>
            <el-input v-model="submitForm.name" placeholder="请输入预算标题" clearable />
          </el-form-item>
          <el-form-item label="预算类型:" required>
            <el-radio-group v-model="submitForm.template" placement="row">
              <el-radio label="创建模板" :value="1" :customStyle="{ marginRight: '35px' }" />
              <el-radio label="创建预算" :value="2" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="模版列表:">
            <el-row type="flex" gutter="12" class="flex-1">
              <el-col :span="12">
                <el-select v-model="templateType" placeholder="请选择模版类型" @change="handleTemplateTypeChange">
                  <el-option
                    v-for="item in templateTypeOptions"
                    :key="item.label"
                    :label="item.label"
                    :value="item.label" />
                </el-select>
              </el-col>
              <el-col :span="12">
                <el-select
                  v-model="submitForm.calculate_id"
                  placeholder="请选择模版列表"
                  @change="handleTemplateChange"
                  @visible-change="visibleChange"
                  v-select-loadmore="onLoadmore"
                  popper-class="single-select-loadmore">
                  <el-option
                    v-for="item in templateOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="房屋类型:" required>
            <el-select
              v-model="submitForm.house_number"
              placeholder="请选择房屋类型"
              :disabled="Boolean(submitForm.calculate_id)">
              <el-option v-for="item in houseTypeOptions" :key="item.label" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="成本计算模式:" required v-if="isShow">
            <el-radio-group v-model="submitForm.mode" placement="row">
              <el-radio label="分项直管模式" :value="1" :customStyle="{ marginRight: '35px' }" />
              <el-radio label="基装大包模式" :value="2" />
            </el-radio-group>
          </el-form-item>
          <div class="flex justify-center" @click="handleSave">
            <div class="save-button">提交</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog v-model="templateDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleTemplateClose" :title="templateTitle" />
        <el-form class="px-6 pt-6 flex flex-col gap-6">
          <el-form-item label="预算标题:" required>
            <el-input v-model="calculateTitle" placeholder="请输入预算标题" clearable />
          </el-form-item>
          <div class="flex justify-center" @click="handleTemplateSave">
            <div class="save-button">提交</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog v-model="makeComputeDialog" width="400" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleMakeComputeClose" title="多层数据采集" />
        <view class="flex flex-col overflow-x-auto" style="height: 500px">
          <view
            class="px-5 py-3 flex items-center"
            :style="{ borderBottom: index == housesInfo!.length - 1 ? '' : '1px solid #888888' }"
            v-for="(item, index) in housesInfo"
            :key="index">
            <view class="flex justify-center items-center flex-shrink-0 w-[110px]">
              <img :src="handleHousePic(index)" class="w-[110px] h-[73px]" />
            </view>
            <view class="flex flex-col gap-2 ml-5 mr-3 flex-1">
              <div class="text-base font-bold text-black">{{ item.house_name }}</div>
              <view class="grid grid-cols-2" style="gap: 5px 10px">
                <view class="child">
                  <div class="left" :class="item.floor ? 'childActive' : ''"></div>
                  <span class="name">瓷砖数据</span>
                </view>
                <view class="child">
                  <div class="left" :class="item.house ? 'childActive' : ''"></div>
                  <span class="name">户型数据</span>
                </view>
                <view class="child">
                  <div class="left" :class="item.carpentry ? 'childActive' : ''"></div>
                  <span class="name">木工数据</span>
                </view>
                <view class="child">
                  <div class="left" :class="item.wardrobe ? 'childActive' : ''"></div>
                  <span class="name">衣柜数据</span>
                </view>
                <view class="child">
                  <div class="left" :class="item.other ? 'childActive' : ''"></div>
                  <span class="name">其他数据</span>
                </view>
              </view>
            </view>
            <view class="flex items-end" style="height: 100%">
              <text class="text-blue-400 text-sm cursor-pointer" @click="handleCollectData(index + 1)">做预算</text>
            </view>
          </view>
        </view>
        <div class="flex flex-col gap-3 mt-3">
          <div
            class="flex justify-center"
            v-if="currentInfo?.template == 1 && currentInfo?.check_gather != 1"
            @click="handleSubmit">
            <div class="save-button">保存模版</div>
          </div>
          <div
            class="flex justify-center"
            v-if="currentInfo?.check_gather != 1 && currentInfo?.template == 2"
            @click="handleSubmit">
            <div class="save-button">提交数据</div>
          </div>
          <div
            class="flex justify-center"
            v-if="currentInfo?.check_gather == 1 && currentInfo?.check_lock != 1"
            @click="handleResetData">
            <div class="save-button">提交计算</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </main>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 20px !important;
  flex: 1;
}
.el-form-item:nth-last-child(1) {
  margin-right: 0px !important;
}
::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}
.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #ff9600 !important;
}
::v-deep .el-radio__input.is-checked .el-radio__inner {
  background: #ff9600 !important;
  border-color: #ff9600 !important;
}
.child {
  width: 75px;
  display: flex;
  align-items: center;

  .left {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 12px;
    height: 12px;
    color: #ffffff;
    font-size: 12px;
    border-radius: 2px;
    background: #bfbfbf;
  }

  .childActive {
    background: #3285fe;
  }

  .name {
    font-weight: 400;
    font-size: 12px;
    color: #888888;
    margin-left: 8px;
  }
}
</style>
